package com.cch.datageniebackendmaster.service;

import com.cch.datageniebackendmaster.common.BaseResponse;
import com.cch.datageniebackendmaster.model.enums.ErrorCodeEnum;
import com.cch.datageniebackendmaster.util.ResultUtil;
import com.cch.datageniebackendmaster.util.ThrowUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

@Service
public class UploadService {

    private static final String SECRET_ID = "AKID41pX2Wr551ve8ScdTH7pshJm7JTQ8f3F";
    private static final String SECRET_KEY = "5vc6SwCF8oJbfV5WlrlX7UeZIC8IJOSI";
    private static final String BUCKET_NAME = "cch-file-1314484302";
    private static final String REGION_NAME = "ap-chengdu";
    private static final String COS_DOMAIN = "https://cch-file-1314484302.cos.ap-chengdu.myqcloud.com";

    private COSClient cosClient;

    /**
     * 上传文件至 /static 文件夹
     *
     * @param file
     * @return 存储到数据库的图片地址
     */
    public BaseResponse<String> uploadLocal(MultipartFile file) {
        ThrowUtil.throwIf(Objects.isNull(file), ErrorCodeEnum.PARAMS_ERROR);
        // 当前时间毫秒数+图片名称
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        // 文件夹路径
        String filePath = System.getProperty("user.dir") + System.getProperty(
                "file.separator") + "static";
        // 文件夹不存在新建
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        // 图片路径
        File file2 = new File(filePath + System.getProperty("file.separator") + fileName);
        // 存图片至文件夹
        try {
            file.transferTo(file2);
        } catch (IOException e) {
            e.printStackTrace();
            return ResultUtil.error(ErrorCodeEnum.OPERATION_ERROR);
        }
        // 存储到数据库的图片相对路径
        String path = "/static/" + fileName;
        return ResultUtil.success(path);
    }

    public UploadService() {
        // 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
        // 设置bucket的地域
        ClientConfig clientConfig = new ClientConfig(new Region(REGION_NAME));
        // 生成cos客户端
        cosClient = new COSClient(cred, clientConfig);
    }

    /**
     * 上传文件至 腾讯云cos
     *
     * @param file
     * @return
     */
    public BaseResponse<String> uploadCos(MultipartFile file) throws IOException {
        ThrowUtil.throwIf(Objects.isNull(file), ErrorCodeEnum.PARAMS_ERROR);

        // 文件名生成策略
        String originalFilename = file.getOriginalFilename();

        // 创建一个临时文件
        File tempFile = File.createTempFile("temp", null);
        file.transferTo(tempFile);

        try {
            // 删除旧头像
//            if (StrUtil.isNotBlank(oldFilename) && !"user-default.jepg".equals(oldFilename)) {
//                cosClient.deleteObject(BUCKET_NAME, oldFilename);
//            }

            // 上传文件
            PutObjectRequest putObjectRequest = new PutObjectRequest(BUCKET_NAME, originalFilename, tempFile);
            cosClient.putObject(putObjectRequest);

            // 返回文件的访问地址
            return ResultUtil.success(String.format("%s/%s", COS_DOMAIN, originalFilename));
        } finally {
            // 删除临时文件
            if (tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

}
